package com.xjrh.traintravel.collector.netty.handler;

import com.xjrh.common.core.utils.FileUploadUtils;
import com.xjrh.traintravel.collector.common.CRC16M;
import com.xjrh.traintravel.collector.common.CodeConvertor;
import com.xjrh.traintravel.collector.netty.coder.command.AgreementCommandEnum;
import com.xjrh.traintravel.collector.netty.coder.command.AgreementConstant;
import com.xjrh.traintravel.collector.netty.coder.command.AgreementStructure;
import com.xjrh.traintravel.collector.netty.command.data.DataContent;
import com.xjrh.traintravel.collector.netty.command.data.DataFileName;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.IOException;

/**
 * 采集数据上传-指令处理类
 *
 * @author snps
 * @create 2022-02-12 14:31
 * @describe
 **/
@Component
@Slf4j
public class DataHandler extends BaseAgreementHandler {

    /**
     * 得到 采集数据-文件名
     * @param equipmentId 设备标识
     * @param data 上报数据
     * @return DataFileName
     */
    public DataFileName getDataFileName(String equipmentId, String data) {
        DataFileName dataFileName = new DataFileName();
        dataFileName.setEquipmentId(equipmentId);
        dataFileName.setCommonNo(data.substring(0, 2));
        dataFileName.setFileType(Integer.parseInt(data.substring(2, 4), 16));

        int timeValue = 0;
        StringBuilder sbuTime = new StringBuilder();
        sbuTime.append((timeValue = Integer.parseInt(data.substring(4, 6), 16)) >= 10 ? timeValue : "0"+timeValue);
        sbuTime.append((timeValue = Integer.parseInt(data.substring(6, 8), 16)) >= 10 ? timeValue : "0"+timeValue);
        sbuTime.append((timeValue = Integer.parseInt(data.substring(8, 10), 16)) >= 10 ? timeValue : "0"+timeValue);
        sbuTime.append((timeValue = Integer.parseInt(data.substring(10, 12), 16)) >= 10 ? timeValue : "0"+timeValue);
        sbuTime.append((timeValue = Integer.parseInt(data.substring(12, 14), 16)) >= 10 ? timeValue : "0"+timeValue);
        sbuTime.append((timeValue = Integer.parseInt(data.substring(14, 16), 16)) >= 10 ? timeValue : "0"+timeValue);
        dataFileName.setTime(sbuTime.toString());
        dataFileName.setCom(Integer.parseInt(data.substring(34, 36), 16));
        dataFileName.setFrontType(Integer.parseInt(data.substring(36, 38), 16));
        dataFileName.setFrontAccess(Integer.parseInt(data.substring(38, 40), 16));
        // 对：前置通道（对应传感器） 的值进行处理，如果接收的值为：255，则转换为：9（９＝全部传感器）
        // 温度：11FF = 11255 = 119，速度：00FF = 00255 = 009
        if (dataFileName.getFrontAccess() == 255) {
            dataFileName.setFrontAccess(9);
        }
        dataFileName.setTemperature(Integer.parseInt(data.substring(40), 16));

        // 2023-04-17：增加字段-数据日期，解决-跨天采集数据传输情况
        StringBuilder sbuCollectorDate = new StringBuilder("20");
        sbuCollectorDate.append((timeValue = Integer.parseInt(data.substring(4, 6), 16)) >= 10 ? timeValue : "0"+timeValue).append("-");
        sbuCollectorDate.append((timeValue = Integer.parseInt(data.substring(6, 8), 16)) >= 10 ? timeValue : "0"+timeValue).append("-");
        sbuCollectorDate.append((timeValue = Integer.parseInt(data.substring(8, 10), 16)) >= 10 ? timeValue : "0"+timeValue);
        dataFileName.setCollectionDate(sbuCollectorDate.toString());

        return dataFileName;
    }

    /**
     * 回复 收到-采集数据-文件名
     * @param agreement 收到的消息
     * @param channel 客户端连接通道
     */
    public void replyGetDataFileName(AgreementStructure agreement, Channel channel) {
        AgreementStructure replyAgreement = new AgreementStructure();

        // 前导码(4)
        replyAgreement.setPc(AgreementConstant.PC_VALUE);
        // 帧头(1)
        replyAgreement.setSd(AgreementConstant.SD_VALUE);
        // 控制(1)
        replyAgreement.setFc(AgreementCommandEnum.R_84.getValue());
        // MAC地址(6)
        replyAgreement.setAddr(agreement.getAddr());
        // 序号(1)
        // replyAgreement.setSeq(CodeConvertor.intToHexString(1, 1));
        replyAgreement.setSeq(super.getEquipmentSeq(replyAgreement.getAddr()));
        // 长度(2)
        replyAgreement.setLen(CodeConvertor.intToHexString(2, 2));
        // 数据(N)
        replyAgreement.setData("01" + "00");
        // 校验(2)
        String crcValue = CRC16M.calculateCrc(replyAgreement);
        replyAgreement.setFcs(crcValue);
        // 帧尾(1)
        replyAgreement.setFs(AgreementConstant.FS_VALUE);

        super.sendCommand(replyAgreement);
    }

    /**
     * 得到 采集数据-文件内容
     * @param equipment 设备标识
     * @param data 上报数据
     * @return DataContent
     */
    public DataContent getDataContent(String equipment, String data) {
        DataContent dataContent = new DataContent();
        dataContent.setEquipmentId(equipment);
        dataContent.setCommonNo(data.substring(0, 2));
        dataContent.setLastFrameFlag(data.substring(2, 4));
        dataContent.setLength(Integer.parseInt(data.substring(4, 8), 16));
        dataContent.setData(CodeConvertor.hexString2String(data.substring(8)));
        return dataContent;
    }

    /**
     * 处理文件内容
     *  <p>
     *      1. 先把收到的数据，以文件形式保存
     *      2. 最终的处理方式待确定
     *  </p>
     * @return boolean
     */
    public boolean handleDataContent(String fileName, String content) {
        try {
            String filePath = FileUploadUtils.write(null, null, fileName, content);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    /**
     * 回复 收到-采集数据-文件内容
     * @param agreement 收到的消息
     * @param result 结果（00-正常，02-异常）
     * @param channel 客户端连接通道
     */
    public void replyGetDataContent(AgreementStructure agreement, String result, Channel channel) {
        AgreementStructure replyAgreement = new AgreementStructure();

        // 前导码(4)
        replyAgreement.setPc(AgreementConstant.PC_VALUE);
        // 帧头(1)
        replyAgreement.setSd(AgreementConstant.SD_VALUE);
        // 控制(1)
        replyAgreement.setFc(AgreementCommandEnum.R_84.getValue());
        // MAC地址(6)
        replyAgreement.setAddr(agreement.getAddr());
        // 序号(1)
        // replyAgreement.setSeq(CodeConvertor.intToHexString(1, 1));
        replyAgreement.setSeq(super.getEquipmentSeq(replyAgreement.getAddr()));
        // 长度(2)
        replyAgreement.setLen(CodeConvertor.intToHexString(2, 2));
        // 数据(N)
        replyAgreement.setData("02" + "00");
        // 校验(2)
        String crcValue = CRC16M.calculateCrc(replyAgreement);
        replyAgreement.setFcs(crcValue);
        // 帧尾(1)
        replyAgreement.setFs(AgreementConstant.FS_VALUE);

        super.sendCommand(replyAgreement);
    }

}